/***************************************************************************
 * Copyright 2012-2013 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the contract ICT-257367.
 *
 * Authors:
 *      Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.client.publisher.impl;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.BasicProperties.Builder;

import it.txt.ens.client.core.ENSBrokerConnectionParameters;
import it.txt.ens.client.core.ENSEvent;
import it.txt.ens.client.core.factory.ENSBrokerConnectionParametersFactory;
import it.txt.ens.client.impl.BasicENSClient;
import it.txt.ens.client.publisher.ENSPublisher;
import it.txt.ens.client.publisher.ENSPublishingException;
import it.txt.ens.client.publisher.factory.ENSPublisherFactory;
import it.txt.ens.client.util.AMQPConstants;
import it.txt.ens.core.ENSAuthzServiceConnectionParameters;
import it.txt.ens.core.ENSOperation;
import it.txt.ens.core.ENSResource;
import it.txt.ens.core.KeystoreParameters;
import it.txt.ens.core.X509CertificateRetrievalParameters;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactory;
import it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactory;

/**
 * Provides the default implementation of {@link ENSPublisher}.
 * 
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com)
 * @author Domenico Rotondi (TXT e-solutions SpA - domenico.rotondi AT txtgroup.com)
 *
 */
public class BasicENSPublisher extends BasicENSClient implements ENSPublisher{

    public static final String VERSION = "1.0.0";
    public static final String APPLICATION_ID = BasicENSPublisher.class.getName() + Versions.SUBSCRIBER_IMPLEMENTATION;
    private static final Logger LOGGER = Logger.getLogger(BasicENSPublisher.class.getName(),
            "logging-messages/" + BasicENSPublisher.class.getSimpleName());
    private String pattern;
    private String exchange;
    private String userID;
    
    private BasicENSPublisher(String subjectID, ENSResource targetResource,
            Date sessionExpiration, ENSAuthzServiceConnectionParameters authzServiceConnParams,
            KeystoreParameters keystoreParams,
            X509CertificateRetrievalParameters certParams,
            File capabilityDirectory,
            ENSAuthorisationRequestFactory requestFactory,
            ENSAuthorisationResponseFactory responseFactory,
            ENSBrokerConnectionParametersFactory connParamsFactory) {
        super(subjectID, targetResource, ENSOperation.publish, sessionExpiration,
                authzServiceConnParams, keystoreParams, certParams,
                capabilityDirectory, requestFactory, responseFactory, connParamsFactory);
    }

    /* (non-Javadoc)
     * @see it.txt.ens.client.impl.BasicENSClient#useENSBrokerConnectionParameters(it.txt.ens.client.core.ENSBrokerConnectionParameters)
     */
    @Override
    protected void useENSBrokerConnectionParameters(
            ENSBrokerConnectionParameters parameters) {
        pattern = targetResource.getPattern();
        exchange = parameters.getDestinationName();
        userID = parameters.getSubjectID();
    }

    /* (non-Javadoc)
     * @see it.txt.ens.client.publisher.ENSPublisher#publish(it.txt.ens.client.core.ENSEvent)
     */
    @Override
    public void publish(ENSEvent event) throws ENSPublishingException, IllegalArgumentException, IllegalStateException {
        if (!this.isConnected())
            throw new IllegalStateException("The publisher is not connected");
        
        if (event == null)
            throw new IllegalArgumentException("The event to be published cannot be null");
        
        //build the AMQP message properties
        Builder messagePropertiesBuilder = new Builder();
        messagePropertiesBuilder.contentEncoding(event.getContentEncoding())
            .contentType(event.getContentType())
            .deliveryMode(event.isPersistent() ? AMQPConstants.PERSISTENT_DELIVERY : AMQPConstants.NOT_PERSISTENT_DELIVERY)
            .timestamp(event.getTimestamp())
            .userId(userID)
            .appId(APPLICATION_ID)
            .priority(event.getPriority())
            .headers(event.getHeaders());
        BasicProperties properties = messagePropertiesBuilder.build();
        
        try {
            if (null == channel || !channel.isOpen())
                channel = connection.createChannel();
            channel.basicPublish(exchange, pattern, properties, event.getPayload());
            
            if (LOGGER.isLoggable(Level.FINER)) {
                LOGGER.log(Level.FINER, "Published an event on the exchange '" + exchange + "'" +
                    " (pattern: '" + pattern + "') with properties " + properties  + " and a " +
                    MessageFormat.format("{0,number,integer} {0,choice,0#bytes|1#byte|1<bytes}",
                        event.getPayload() == null? 0 : event.getPayload().length) + " payload");
            }
        } catch (IOException e) {
            ENSPublishingException epe = new ENSPublishingException("publisher.genericPublishError", e);
            LOGGER.log(Level.SEVERE, epe.getMessage(), e);
            closeConnection();
            throw epe;
        }
    }
    
    /**
     * Provides the default implementation of {@link ENSPublisherFactory}.<br/>It creates
     * {@link BasicENSPublisher} objects.
     * 
     * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com)
     * @author Domenico Rotondi (TXT e-solutions SpA - domenico.rotondi AT txtgroup.com)
     *
     */
    public static class BasicENSPublisherFactory implements ENSPublisherFactory {

        /* (non-Javadoc)
         * @see it.txt.ens.client.publisher.factory.ENSPublisherFactory#create(java.lang.String, it.txt.ens.core.ENSResource, java.util.Date, it.txt.ens.core.ENSAuthzServiceConnectionParameters, it.txt.ens.core.KeystoreParameters, it.txt.ens.core.X509CertificateRetrievalParameters, java.io.File, it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactory, it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactory, it.txt.ens.client.core.factory.ENSBrokerConnectionParametersFactory, it.txt.ens.client.core.factory.ENSEventFactory)
         */
        @Override
        public ENSPublisher create(
                String subjectID,
                ENSResource targetResource,
                Date sessionExpiration,
                ENSAuthzServiceConnectionParameters accessRequestBrokerConnParams,
                KeystoreParameters keystoreParams,
                X509CertificateRetrievalParameters certParams,
                File capabilityDirectory,
                ENSAuthorisationRequestFactory requestFactory,
                ENSAuthorisationResponseFactory responseFactory,
                ENSBrokerConnectionParametersFactory connParamsFactory) {
            return new BasicENSPublisher(subjectID, targetResource, 
                sessionExpiration, accessRequestBrokerConnParams, keystoreParams,
                certParams, capabilityDirectory, requestFactory, responseFactory, connParamsFactory);
        }
        
    }
}
